<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
  <script src="../../lib/vue.js"></script>
  <!-- <script src="../../lib/vue.min.js"></script> -->
  <link rel="stylesheet" href="../../lib/vant@2.12.54_lib_index.css">
  <link rel="stylesheet" href="../../styles/vant.css" />
  <script src="../../lib/vant@2.12.54_lib_vant.min.js"></script>
  <script src="../../lib/axios-0.18.0.js"></script>
  <script src="../../http/request.js"></script>
  <script src="../../utils/fileCompress.js"></script>
  <script src="../../utils/toFormData.js"></script>
  <script src="../../utils/dateFormat.js"></script>
  <script src="../../areaList/areaList.js"></script>
  <script src="../../areaList/activeAreaList.js"></script>
  <title>代跑跑</title>
  <style>
    .main {
      overflow: scroll;
      height: 85vh;
    }

    .van-tabbar-item__icon {
      font-size: 30px;
    }

    .van-uploader__wrapper {
      flex-wrap: wrap;
    }

    .van-cell.overflow-visible {
      overflow: visible;
      height: 0;
    }

    .van-uploader__upload {
      bottom: 90px;
      left: 0;
    }

    .van-coupon__condition {
      display: none;
    }

    .van-coupon__amount {
      color: var(--van-primary);
    }

    .van-coupon-list__bottom .van-button--danger {
      background-color: var(--van-primary);
      border: 1px solid var(--van-primary);
    }

    .van-coupon-list__list {
      height: calc(60vh - 48px) !important;
    }

    .van-dialog__confirm,
    .van-dialog__confirm:active {
      color: var(--van-primary);
    }

    .description-box .van-cell {
      margin-top: 0;
      padding-top: 0;
    }

    .field__label-indent .van-field__label {
      width: 3.0rem;
    }



    .field__label-indent-time .van-field__label {
      width: 5.0rem;
      margin-right: 0;
    }

    .field__label-indent-time .van-radio__label {
      margin-left: 0;
    }

    .description-box-mark .van-cell__label {
      margin-top: 2px;
      color: red;
    }

    .van-radio--horizontal {
      margin-right: 5px;
    }
  </style>
</head>

<body>
  <div id="app">
    <van-nav-bar title="下单"></van-nav-bar>
    <div class="main">
      <van-form @submit="onSubmit">
        <van-cell-group title="地址信息" inset>

          <!-- 联系电话 -->
          <van-field v-model="phone" type="number" required name="phone" label="联系电话：" placeholder="请输入电话号码"
                     :rules="[{ validator:validatorForPhone, required: true, message: '请输入正确的国内电话号码' }]"></van-field>

          <!-- 送达地址 -->
          <van-field readonly clickable required name="address" :value="address" label="送达地址：" placeholder="点击选择送达地址"
                     @click="isShowAddressList = true" :rules="[{ required: true, message: '请选择送达地址' }]"></van-field>

          <!-- 送达地址弹出层 -->
          <van-popup v-model="isShowAddressList" round position="bottom">
            <van-tabs v-model="areaList">
              <van-tab title="静园">
                <van-area title="静园" :area-list="JingYuanAreaList" @confirm="getAddress"
                          @cancel="isShowAddressList = false"></van-area>
              </van-tab>
              <van-tab title="怡园">
                <van-area title="怡园" :area-list="YiYuanAreaList" @confirm="getAddress"
                          @cancel="isShowAddressList = false"></van-area>
              </van-tab>
            </van-tabs>
          </van-popup>

          <!-- 送达时间 -->
          <van-field :value="expectTime" required :border="false" readonly name="expectTime" label="送达时间："
                     :rules="[{ required: true, message: '请选择送达时间' }]">
          </van-field>

        </van-cell-group>

        <van-cell-group inset title="取件信息">
          <!-- 取件信息 -->
          <van-field v-model="packageInfo" required rows="4" name="packageInfo" :border="false" autosize label="取件信息："
                     type="textarea" maxlength="100" placeholder="请粘贴取件信息或上传图片" show-word-limit
                     :rules="[{ validator:validatorForPackageInfo, message: '请粘贴取件信息或上传取件图片' }]"></van-field>

          <!-- 取件图片集 -->
          <van-field name="images" class="overflow-visible" :border="false">
            <template #input>
              <van-uploader v-model="images" :max-count="maxCount" :multiple="true" accept="image/*"></van-uploader>
            </template>
          </van-field>

          <!-- <div class="description-box-mark" style="text-align: center;"> -->
          <div class="description-box-mark">
            <van-cell style="padding: 0 16px;" label="中件和重件需要单独配送，请同学单独下单。" title=""></van-cell>
            <van-cell style="padding: 0 16px;" label="牛奶，哑铃和整箱水果请下重件。" title=""></van-cell>
            <van-cell style="padding: 0 16px;" label="?-1-xxxx和?-6-xxxx请根据商品下中件和重件" title=""></van-cell>
          </div>

          <!-- 快递件数 -->
          <van-field class="field__label-indent-time" v-if="orderSpec === 1||orderSpec === 2" class="amount__containter"
                     name="count" label="快递件数：" readonly>
            <template #input>
              <van-radio-group v-model="count" direction="horizontal">
                <van-radio v-for="item in maxPackageCount" :key="item" :name="item">{{item}}</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field class="field__label-indent" name="radio" label="规格：">
            <template #input>
              <van-radio-group v-model="orderSpec" direction="horizontal">
                <van-radio :name=0>小件</van-radio>
                <van-radio :name=3>中件</van-radio>
                <van-radio :name=4>重件</van-radio>
                <van-radio :name=1>多件</van-radio>
                <van-radio :name=2>超多件</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <!-- 备注 -->
          <van-field v-model="remark" name="remark" label="备注：" placeholder="请输入备注信息"></van-field>

          <div class="description-box-mark">
            <van-cell label="物流公司为顺丰，或取件码为88、50开头的快递，请备注姓名和手机尾号" title="">
            </van-cell>
          </div>

          <!-- 优惠券单元格 -->
          <van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showCouponList"></van-coupon-cell>

          <!-- 悬赏 -->
          <van-field name="amount" label="悬赏：">
            <template #input>
              <!-- 打折模板 -->
              <span v-if="isUseDiscount">
                <span style="color: red;">
                  ￥ {{discountAmount.toFixed(2)}}&nbsp;
                </span>
                <del style="color: red;">
                  <span style="color: #323233;">￥ {{amount.toFixed(2)}}</span>
                </del>
              </span>

              <!-- 常规模板 -->
              <span v-else-if="!isUseDiscount" style="color: #323233;">￥ {{amount.toFixed(2)}} &nbsp;&nbsp;
                <span v-if="!isFirstOrder" style="color: red;">首单优惠已使用</span>
              </span>
            </template>
          </van-field>

        </van-cell-group>

        <!-- 提交按钮 -->
        <div style="margin: 16px;">
          <van-button round block :loading="isLoading" type="primary" native-type="submit">
            帮我取
          </van-button>
        </div>

      </van-form>

      <!-- 优惠券列表弹出层 -->
      <van-popup v-model="isShowCouponList" round position="bottom" style="height: 60vh; padding-top: 4px;">
        <van-coupon-list :coupons="coupons" :show-exchange-bar="false" :chosen-coupon="chosenCoupon"
                         :disabled-coupons="disCoupons" @change="changeCoupon">
        </van-coupon-list>
      </van-popup>

    </div>

    <!-- 底层标签页 -->
    <van-tabbar class="tabbar" v-model="active" @change="onChange">
      <van-tabbar-item icon="wap-home" name="home">主页</van-tabbar-item>
      <van-tabbar-item icon="shop" name="information">商家</van-tabbar-item>
      <van-tabbar-item icon="thumb-circle" name="distribute">下单</van-tabbar-item>
      <van-tabbar-item icon="bars" name="order">订单</van-tabbar-item>
      <van-tabbar-item icon="manager" name="personalCenter">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</body>
<script>
  var APPID = "wx576478355cd34bb0"
  new Vue({
    el: "#app",
    data() {
      return {
        isPayVersion: true, // 是否开启支付版本
        isFirstOrder: false, // 是否为首单
        orderSpec: 1, // 订单规格
        phone: '', // 联系电话
        address: '', // 送达地址
        packageInfo: '', // 取件信息
        images: [], // 取件图片数组, 用于回显
        count: 1, // 快递件数
        remark: '', // 备注
        isUseDiscount: false, // 是否使用折扣
        isShowAddressList: false, // 控制展示地址选择的弹出层
        isShowCouponList: false, // 控制显示优惠券列表的弹出层 
        isShowPicker: false, // 控制展示送达时间的弹出层
        active: 'distribute', // 控制标签栏的显示
        isLoading: false, // 提交按钮是否禁用  
        chosenCoupon: -1, // 默认选择的优惠券
        coupons: [], // 可用优惠券列表
        disCoupons: [], // 不可用优惠券列表
        areaList: '', // 一级地址                          
        JingYuanAreaList: JingYuanAreaList, // 静园地址列表
        YiYuanAreaList: YiYuanAreaList, // 怡园地址列表
        TeachingBuildingAreaList: TeachingBuildingAreaList, // 教学楼地址列表
        OtherAreaList: OtherAreaList, // 其他地址列表
        // boyAreaList: ['静园3', '静园6A', '静园6B', '静园14A', '静园14B', '静园15A', '静园15B', '静园16',
        //   '怡园13', '怡园16', '怡园5B', '怡园3A', '怡园3B', '怡园4A', '怡园4B', '怡园8A', '怡园8B', '怡园9A', '怡园9B']
      }
    },
    methods: {
      // 联系方式表单校验
      validatorForPhone(val) {
        return /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(val)
      },
      // 取件信息表单校验
      validatorForPackageInfo() {
        return !!(this.images.length || this.packageInfo)
      },
      // 确认送达地址
      getAddress(values) {
        // 拼接要展示的地址
        this.address = values.filter((item) => !!item).map((item) => item.name).join('/')
        this.isShowAddressList = false
      },
      // 展示优惠券列表
      showCouponList() {
        this.isShowCouponList = true
        if (this.chosenCoupon === -1) {
          setTimeout(() => {
            const inputs = document.querySelectorAll('.van-checkbox__icon .van-icon.van-icon-success')
            for (const item of inputs) {
              item.style.borderColor = '#c8c9cc'
              item.style.backgroundColor = '#fff'
            }
          }, 1)
        }
      },
      // 切换优惠券
      changeCoupon(index) {
        this.isShowCouponList = false
        if (index !== -1) {
          setTimeout(() => {
            const inputs = document.querySelectorAll('.van-checkbox__icon .van-icon.van-icon-success')
            inputs[index].style.borderColor = '#2ED0DF'
            inputs[index].style.backgroundColor = '#2ED0DF'
          }, 1)
        }
        this.chosenCoupon = index
      },
      // Tabbar 跳转其他页面
      onChange(index) {
        if (index === 'home') {
          location.href = '../../home.html?flag=0'
        } else {
          location.href = `../../${index}.html`
        }
      },
      // 提交订单
      onSubmit(values) {
        this.$dialog.confirm({
          message: `请确认您的送达地址:<span style="color: #ff0000;">${this.address}</span>`,
        }).then(async () => {
          // 订单提交提示信息
          this.$notify({
            message: '订单提交中，请稍后~~',
            color: '#ffffff',
            background: '#ff976a',
            duration: 2000,
          })
          this.isLoading = true
          // 调用 toFormData 函数，将值存进 FormData 对象
          const formData = await toFormData(values)
          if (this.orderSpec === 0) {
            formData.append('productId', 15) // 增加商品类型 小件
            formData.set('count', 1)
          } else if (this.orderSpec === 1) {
            formData.append('productId', 16) // 增加商品类型 多件
          } else if (this.orderSpec === 2) {
            formData.append('productId', 17) // 增加商品类型 超多件
          } else if (this.orderSpec === 3) {
            formData.append('productId', 10) // 增加商品类型 中件
            formData.set('count', 1)
          } else if (this.orderSpec === 4) {
            formData.append('productId', 14) // 增加商品类型 重件
            formData.set('count', 1)
          }
          formData.append('isUseDiscount', this.isUseDiscount)
          this.isUseDiscount
            ? formData.set('amount', this.discountAmount)
            : formData.set('amount', this.amount)
          if (this.isUseDiscount) formData.append('couponId', this.coupons[this.chosenCoupon].couponId)
          // 调用发单接口
          axios({
            method: 'POST',
            url: '/user/order/distribute',
            // 设置 请求头 formData 格式
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            data: formData
          }).then(res => {
            if (res.code === 1) {
              if (this.isPayVersion) {
                // 支付版本
                const data = res.data
                if (typeof WeixinJSBridge == "undefined") {
                  if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
                  } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
                  }
                } else {
                  WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', {
                    "appId": APPID,  //公众号ID，由商户传入
                    "timeStamp": data.timeStamp, //时间戳，自1970年以来的秒数
                    "nonceStr": data.nonceStr, //随机串
                    "package": data.prepayId,
                    "signType": "RSA", //微信签名方式：
                    "paySign": data.paySign //微信签名
                  }, (res) => {
                    if (res.err_msg === "get_brand_wcpay_request:ok") {
                      // 使用以上方式判断前端返回,微信团队郑重提示：
                      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                      this.$notify({
                        message: '订单支付成功,将在2秒后跳转至订单~~',
                        color: '#ffffff',
                        background: '#2ED0DF',
                        duration: 2000,
                      })
                      setTimeout(() => {
                        location.href = `../../order.html`
                      }, 2000)
                    } else {
                      this.$notify({
                        message: '订单支付失败,请重新下单，如有疑问请添加客服解决~~',
                        color: '#ffffff',
                        background: '#ee0a24',
                        duration: 2000,
                      })
                      this.isLoading = false
                    }
                  }
                  )
                }
              } else {
                // 非支付版本
                this.$notify({
                  message: '订单支付成功,将在2秒后跳转至订单~~',
                  color: '#ffffff',
                  background: '#2ED0DF',
                  duration: 2000,
                })
                setTimeout(() => {
                  location.href = `../../order.html`
                }, 2000)
              }
            }
          })
        }).catch(() => {
        })
      },
    },
    async mounted() {
      const res = await axios({ method: 'GET', url: '/user/user/getDA' })
      this.phone = res.data.phone ? res.data.phone : ''
      if (res.data.address) {
        const firstAddress = res.data.address.slice(0, 2)
        if (firstAddress !== '静园' && firstAddress !== '怡园') {
          this.address = ''
        } else {
          this.address = res.data.address
        }
      }
      this.isFirstOrder = res.data.isNew
      res.data.coupons.forEach(item => {
        for (let count = 0; count < item.count; count++) {
          this.coupons.push(item)
        }
      })
      res.data.disCoupons.forEach(item => {
        for (let count = 0; count < item.count; count++) {
          this.disCoupons.push(item)
        }
      })
    },
    watch: {
      // 这里强行改的图片上传图标位置，最好不要乱动  蛆:liuwy
      images(newVal, oldVal) {
        const newImagesLength = newVal.length
        const oldImagesLength = oldVal.length
        if (newImagesLength > 0) {
          const imageDiv = document.querySelector('.van-cell.overflow-visible')
          imageDiv.style.height = '100px'
        } else {
          const imageDiv = document.querySelector('.van-cell.overflow-visible')
          imageDiv.style.height = '0px'
        }
        if (newImagesLength < this.maxCount && oldImagesLength !== this.maxCount) {
          const uploader = document.querySelector('.van-uploader__upload')
          uploader.style.left = '0px'
          setTimeout(() => {
            const uploader = document.querySelector('.van-uploader__upload')
            uploader.style.left = `${-88 * newImagesLength}px`
          }, 1)
        } else if (newImagesLength < this.maxCount && oldImagesLength === this.maxCount) {
          setTimeout(() => {
            const uploader = document.querySelector('.van-uploader__upload')
            uploader.style.left = `${-88 * newImagesLength}px`
          }, 1)
        } else if (newImagesLength === this.maxCount) {
          setTimeout(() => {
            const preview = document.querySelector('.van-uploader__preview:last-child')
            preview.style.left = '0px'
          }, 1)
        }
      },
      chosenCoupon(newVal) {
        newVal === -1 ? this.isUseDiscount = false : this.isUseDiscount = true
      },
      orderSpec(newVal) {
        if (!newVal) {
          if (this.images.length !== 0) {
            this.images = [this.images[0]]
          }
        }
      }
    },
    computed: {
      // 固定的期待时间
      expectTime: {
        get() {
          const date = new Date()
          const today = new Date()
          const tomorrow = new Date()
          tomorrow.setDate(tomorrow.getDate() + 1)
          if (date.getHours() < 18) {
            return `${today.getMonth() + 1}-${today.getDate()} 19:30-20:30`
          } else {
            return `${today.getMonth() + 1}-${tomorrow.getDate()} 19:30-20:30`
          }
        },
        set() {
        }
      },
      discountAmount: {
        get() {
          const discountAmount = ((this.amount * 100) - this.coupons[this.chosenCoupon].value) / 100
          if (discountAmount < 0.1) return 0.1
          else return discountAmount
        },
        set() {
        }
      },
      // 最大图片数
      maxCount: {
        get() {
          if (this.orderSpec === 1 || this.orderSpec === 2) return 3
          else return 1
        },
        set() {
        }
      },
      // 初始金额
      amount: {
        get() {
          if (this.orderSpec === 1) return 2.50
          else if (this.orderSpec === 2) return 4.00
          else if (this.orderSpec === 3) return 1.50
          else if (this.orderSpec === 4) return 3.00
          else return 1.00
        },
        set() {
        }
      },
      // 最大可选件数
      maxPackageCount: {
        get() {
          if (this.orderSpec === 1) return [1, 2, 3]
          else if (this.orderSpec === 2) return [1, 2, 3, 4, 5]
          else return [1]
        },
        set() {
        }
      }

    }
  })

</script>

</html>